package com.interview.server.controller;

import com.interview.server.domain.File;
import com.interview.server.domain.Result;
import com.interview.server.service.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 文件上传Controller
 *
 * @author shaobin
 * @date 2021-03-29
 */

@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private IFileService fileService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询文件元数据
     *
     * @param file 文件
     * @return 文件元数据
     */
    @PostMapping("/upload")
    public Result fileUpload(@RequestParam("uploadFile") MultipartFile file) {
        try {
            String uuid = fileService.uploadFile(file);
            return Result.success("操作成功",uuid);
        }catch (IOException e){
            logger.error(e.getMessage(),e);
            return Result.error();
        }
    }

    /**
     * 查询文件元数据
     *
     * @param uuid 文件元数据ID
     * @param response HttpServletResponse
     * @return 文件元数据
     */
    @GetMapping("/download/{uuid}")
    public Result fileDownload(@PathVariable("uuid") String uuid, HttpServletResponse response){
        try {
            fileService.downloadFileByUuid(uuid, response.getOutputStream());
        }catch (FileNotFoundException e){
            logger.error(e.getMessage(),e);
            return Result.fileError(e.getMessage());
        }catch (IOException e){
            logger.error(e.getMessage(),e);
            return Result.fileError();
        }
        return Result.success();
    }

    /**
     * 查询文件元数据
     *
     * @param uuid 文件元数据ID
     * @return 文件元数据
     */
    @GetMapping("/meta/{uuid}")
    public Result fileMetaInfo(@PathVariable("uuid") String uuid){
        File file = fileService.selectFileByUuid(uuid);
        if(file != null){
            return Result.success(file);
        }
        return Result.error("没有对应的元数据");
    }


}
